package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Value("${tencent.map.key}")
    private String key;
    private final RestTemplate restTemplate;
    /**
     * 通过腾讯地图预估驾驶路线、距离、时间
     *
     * @param calculateDrivingLineForm
     * @return
     */
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        String txMapUrl = "https://apis.map.qq.com/ws/direction/v1/driving/?" +
                "from={from}&to={to}&output=json&callback=cb&key={key}";
        HashMap<String, String> params = new HashMap<>();
        String from = calculateDrivingLineForm.getStartPointLatitude().toString()
                    + "," + calculateDrivingLineForm.getStartPointLongitude().toString();
        String to = calculateDrivingLineForm.getStartPointLatitude().toString()
                    + "," + calculateDrivingLineForm.getEndPointLongitude().toString();
        params.put("from",from);
        params.put("to",to);
        params.put("key",key);
        JSONObject jsonObject = restTemplate.getForObject(txMapUrl, JSONObject.class, params);
        int status = jsonObject.getIntValue("status");
        if(status != 0){
         throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }

        //封装响应vo
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject route = result.getJSONArray("routes").getJSONObject(0);
        //获取预估距离
        int distance = route.getIntValue("distance");
        BigDecimal dis = new BigDecimal(distance).divide(new BigDecimal("1000")).
                            setScale(2, RoundingMode.HALF_UP);
        drivingLineVo.setDistance(dis);
        //获取预估时间
        int duration = route.getIntValue("duration");
        drivingLineVo.setDuration(new BigDecimal(duration));
        //获取预估路线
        JSONArray polyline = route.getJSONArray("polyline");
        drivingLineVo.setPolyline(polyline);

        return drivingLineVo;
    }
}
